import markdown2


def md2html(in_path: str, out_path: str, extras: list = None):
    """
    将Markdown文件转换为HTML文件

    Args:
        in_path: 输入的Markdown文件路径
        out_path: 输出的HTML文件路径
        extras: 要启用的markdown2扩展功能列表
    """
    # 默认启用的扩展功能
    if extras is None:
        extras = [
            "tables",  # 表格支持
            "fenced-code-blocks",  # 围栏代码块
            "strike",  # 删除线
            "footnotes",  # 脚注
            "header-ids",  # 标题ID自动生成
            "toc",  # 目录生成
            "task_list",  # 任务列表（GitHub风格复选框）
            "smarty-pants",  # 智能标点转换
            "metadata",  # 元数据提取
            "cuddled-lists",  # 紧密列表
            "code-friendly",  # 代码友好模式
            "target-blank-links",  # 链接在新窗口打开
            "breaks",  # 换行控制
            "pyshell",  # Python交互式会话支持
        ]

    with open(in_path, "r", encoding="utf-8") as input_file:
        text = input_file.read()

    # 使用markdown2进行转换，启用更多扩展
    html_result = markdown2.markdown(text, extras=extras)

    # 构建完整的HTML文档
    html_content = _build_complete_html(html_result, extras)

    with open(out_path, "w", encoding="UTF-8") as html_file:
        html_file.write(html_content)


def _build_complete_html(html_result, extras):
    """
    构建完整的HTML文档，包含CSS样式和目录

    Args:
        html_result: markdown2转换的结果
        extras: 启用的扩展功能列表

    Returns:
        完整的HTML文档内容
    """
    html_parts = []

    # HTML文档头部
    html_parts.append(
        """<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">"""
    )

    # 添加元数据（如果存在）
    if hasattr(html_result, "metadata") and html_result.metadata:
        metadata = html_result.metadata
        if "title" in metadata:
            html_parts.append(f'    <title>{metadata["title"]}</title>')
        if "author" in metadata:
            html_parts.append(
                f'    <meta name="author" content="{metadata["author"]}">'
            )
        if "description" in metadata:
            html_parts.append(
                f'    <meta name="description" content="{metadata["description"]}">'
            )
        if "keywords" in metadata:
            keywords = (
                ", ".join(metadata["keywords"])
                if isinstance(metadata["keywords"], list)
                else metadata["keywords"]
            )
            html_parts.append(f'    <meta name="keywords" content="{keywords}">')

    # 添加CSS样式
    html_parts.append("    <style>")
    html_parts.append(_get_default_css())
    html_parts.append("    </style>")

    # 如果启用了数学公式，添加MathJax支持
    if "latex" in extras:
        html_parts.append(
            """    <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    <script>
        window.MathJax = {
            tex: {
                inlineMath: [['$', '$'], ['\\(', '\\)']],
                displayMath: [['$$', '$$'], ['\\[', '\\]']]
            }
        };
    </script>"""
        )

    # 如果启用了Mermaid图表，添加Mermaid支持
    if "mermaid" in extras:
        html_parts.append(
            """    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script>
        mermaid.initialize({startOnLoad:true});
    </script>"""
        )

    html_parts.append("</head>")
    html_parts.append("<body>")

    # 添加目录（如果存在）
    if hasattr(html_result, "toc_html") and html_result.toc_html:
        html_parts.append('<div class="table-of-contents">')
        html_parts.append("<h2>目录</h2>")
        html_parts.append(html_result.toc_html)
        html_parts.append("</div>")

    # 主要内容
    html_parts.append('<div class="content">')
    html_parts.append(str(html_result))
    html_parts.append("</div>")

    # 添加脚注样式脚本（如果有脚注）
    if "footnotes" in extras:
        html_parts.append(
            """<script>
// 脚注悬停效果
document.querySelectorAll('a[href^="#fn:"]').forEach(function(link) {
    link.addEventListener('mouseenter', function() {
        this.style.backgroundColor = '#ffeb3b';
    });
    link.addEventListener('mouseleave', function() {
        this.style.backgroundColor = '';
    });
});
</script>"""
        )

    html_parts.append("</body>")
    html_parts.append("</html>")

    return "\n".join(html_parts)


def _get_default_css():
    """
    获取默认的CSS样式

    Returns:
        CSS样式字符串
    """
    return """
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Noto Sans', sans-serif;
            line-height: 1.6;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            color: #333;
        }
        
        /* 目录样式 */
        .table-of-contents {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .table-of-contents h2 {
            margin-top: 0;
            color: #495057;
        }
        
        .table-of-contents ul {
            list-style: none;
            padding-left: 0;
        }
        
        .table-of-contents li {
            margin: 5px 0;
        }
        
        .table-of-contents a {
            text-decoration: none;
            color: #007bff;
        }
        
        .table-of-contents a:hover {
            text-decoration: underline;
        }
        
        /* 代码样式 */
        code {
            background: #f1f3f4;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'SFMono-Regular', 'Consolas', 'Liberation Mono', 'Menlo', monospace;
            font-size: 0.9em;
        }
        
        pre {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 16px;
            overflow-x: auto;
            font-family: 'SFMono-Regular', 'Consolas', 'Liberation Mono', 'Menlo', monospace;
        }
        
        pre code {
            background: none;
            padding: 0;
            border-radius: 0;
        }
        
        /* 引用块样式 */
        blockquote {
            border-left: 4px solid #007bff;
            padding-left: 20px;
            margin: 20px 0;
            color: #6c757d;
            font-style: italic;
        }
        
        /* 表格样式 */
        table {
            border-collapse: collapse;
            width: 100%;
            margin: 20px 0;
        }
        
        th, td {
            border: 1px solid #dee2e6;
            padding: 12px;
            text-align: left;
        }
        
        th {
            background: #f8f9fa;
            font-weight: 600;
        }
        
        /* 任务列表样式 */
        .task-list-item {
            list-style: none;
        }
        
        .task-list-item input[type="checkbox"] {
            margin-right: 8px;
        }
        
        /* 脚注样式 */
        .footnotes {
            border-top: 1px solid #e9ecef;
            margin-top: 40px;
            padding-top: 20px;
            font-size: 0.9em;
        }
        
        .footnotes ol {
            padding-left: 20px;
        }
        
        .footnotes li {
            margin: 8px 0;
        }
        
        a[href^="#fn:"] {
            text-decoration: none;
            color: #007bff;
            font-weight: bold;
            padding: 2px 4px;
            border-radius: 3px;
            transition: background-color 0.2s;
        }
        
        /* 警告框样式 */
        .admonition {
            margin: 20px 0;
            padding: 16px;
            border-radius: 6px;
            border-left: 4px solid;
        }
        
        .admonition.note {
            background: #e7f3ff;
            border-color: #0366d6;
        }
        
        .admonition.warning {
            background: #fff5b4;
            border-color: #d1b910;
        }
        
        .admonition.danger {
            background: #ffeaea;
            border-color: #d73a49;
        }
        
        .admonition.info {
            background: #f0f9ff;
            border-color: #0969da;
        }
        
        .admonition.tip {
            background: #f0fff4;
            border-color: #28a745;
        }
        
        /* 键盘按键样式 */
        kbd {
            background: #f6f8fa;
            border: 1px solid #d1d9e0;
            border-radius: 3px;
            box-shadow: inset 0 -1px 0 #d1d9e0;
            color: #444d56;
            display: inline-block;
            font-family: SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;
            font-size: 11px;
            line-height: 10px;
            padding: 3px 5px;
            vertical-align: middle;
        }
        
        /* 分割线样式 */
        hr {
            border: none;
            height: 1px;
            background: linear-gradient(to right, transparent, #e9ecef, transparent);
            margin: 30px 0;
        }
        
        /* 链接样式 */
        a {
            color: #007bff;
            text-decoration: none;
        }
        
        a:hover {
            text-decoration: underline;
        }
        
        /* 标题样式 */
        h1, h2, h3, h4, h5, h6 {
            margin-top: 24px;
            margin-bottom: 16px;
            font-weight: 600;
            line-height: 1.25;
        }
        
        h1 { border-bottom: 1px solid #e9ecef; padding-bottom: 8px; }
        h2 { border-bottom: 1px solid #e9ecef; padding-bottom: 8px; }
        
        /* 图片样式 */
        img {
            max-width: 100%;
            height: auto;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        /* 徽章样式 */
        img[src*="shields.io"], img[src*="badge"] {
            box-shadow: none;
            border-radius: 4px;
            margin: 2px;
        }
        
        /* 高亮文本样式 */
        mark {
            background: #ffeb3b;
            padding: 2px 4px;
            border-radius: 3px;
        }
        
        /* 插入文本样式 */
        ins {
            background: #d4edda;
            text-decoration: none;
            padding: 2px 4px;
            border-radius: 3px;
        }
        
        /* 删除文本样式 */
        del {
            background: #f8d7da;
            padding: 2px 4px;
            border-radius: 3px;
        }
        
        /* 剧透标签样式 */
        .spoiler {
            background: #000;
            color: #000;
            padding: 2px 4px;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .spoiler:hover {
            color: #fff;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .table-of-contents {
                padding: 15px;
            }
            
            pre {
                padding: 12px;
                font-size: 14px;
            }
            
            table {
                font-size: 14px;
            }
            
            th, td {
                padding: 8px;
            }
        }
    """


if __name__ == "__main__":
    md2html("test/example.md", "test/example.html")
